package com.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.project.entity.Admin;
import com.project.entity.BaseResult;
import com.project.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @PostMapping("register")
    public BaseResult<String> register(HttpServletRequest request, @RequestBody Admin admin){
        log.info("管理员注册信息：{}",admin.toString());
        String password=admin.getAdminPassword();
        Long Id =admin.getId();
        admin.adminStatus=1;
        admin.adminKind="common";
        adminService.save(admin);
        return BaseResult.ok("管理员注册成功");
    }
    @PostMapping("/login")
    public BaseResult<Admin> login(HttpServletRequest request, @RequestBody Admin admin) {

        //1、获取密码
        String password = admin.getAdminPassword();
        //2、根据页面提交的管理员账号查询数据库
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getId, admin.getId());
        Admin adm = adminService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if (adm == null) {
            return BaseResult.fail("登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!adm.getAdminPassword().equals(password)) {
            return BaseResult.fail("登录失败");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (adm.getAdminStatus() == 0) {
            return BaseResult.fail("登录失败");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("admin", adm.getId());
        return BaseResult.ok(adm);
    }
    @PostMapping("/logout")
    public BaseResult<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("admin");
        return BaseResult.ok("退出成功");
    }
    @PostMapping("/edit")
    public BaseResult<String> edit(@RequestBody Admin admin,HttpServletRequest request){
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        Long id = (Long) request.getSession().getAttribute("admin");
        queryWrapper.eq(Admin::getId, id);
        Admin adm = adminService.getOne(queryWrapper);
        if(adm.getAdminStatus()==1&&adm.getAdminKind()=="超级管理员"){
        adminService.updateById(admin);
        return BaseResult.ok("更新成功");
        }
        return BaseResult.fail("更新失败");
    }


}
